package com.openapi.protocol;

import com.openapi.config.RedisConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


public class Server implements Runnable{
    private static final Logger log = LoggerFactory.getLogger(Server.class);
    private final int port;
    private final String serviceAPI;
    private final RedisConfig redisConfig;
    public  static Map<String, ChannelHandlerContext> map = new HashMap<String, ChannelHandlerContext>();
    public final static byte[] mediaIdentifier = new byte[]{0x23,0x23,0x43,0x4d,0x44,0x5e};


    public Server(int port, String serviceAPI,RedisConfig redisConfig) {
        this.port = port;
        this.serviceAPI = serviceAPI;
        this.redisConfig = redisConfig;
    }

    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 10240);
            sb.group(group, bossGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class) // 指定使用的channel
                    .localAddress(this.port)// 绑定监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            log.info("武汉依迅：有一客户端链接到本服务端");
                            log.info("IP:" + ch.remoteAddress().getHostName());
//                            ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
//                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("\r".getBytes())));
                            //ch.pipeline().addFirst(new DelimiterBasedFrameDecoder(2048, Unpooled.copiedBuffer(mediaIdentifier)));
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, Unpooled.copiedBuffer(mediaIdentifier)));
                            ch.pipeline().addLast(new ServerHandler(serviceAPI,redisConfig)); // 客户端触发操作
                            ch.pipeline().addLast(new ByteArrayEncoder());
                        }
                    });
            ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
            log.info(Server.class + " 启动正在监听： " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 关闭服务器通道
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                group.shutdownGracefully().sync(); // 释放线程池资源
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                bossGroup.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }



}